package edu.hubu.config;

import edu.hubu.authentication.JwtAuthenticationFilter;
import edu.hubu.service.impl.TokenService;
import edu.hubu.service.impl.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author moonlan
 * @date 2020/10/20 下午5:12
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthenticationProvider provider;
    private final UserService userService;
    private final AuthenticationManager authManager;
    private final UserDetailsService userDetailsService;
    private final TokenService tokenService;

    public SpringSecurityConfig(AuthenticationProvider provider, UserService userService, AuthenticationManager authManager, @Qualifier("userService") UserDetailsService userDetailsService, TokenService tokenService) {
        this.provider = provider;
        this.userService = userService;
        this.authManager = authManager;
        this.userDetailsService = userDetailsService;
        this.tokenService = tokenService;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/user/code_paint", "/announcement/search", "/announcement/search_like", "/announcement/count", "/course/search", "/course/search_like", "/course/count");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/user/login").anonymous();
        http.authorizeRequests().antMatchers("/**").authenticated();
        http.addFilter(new JwtAuthenticationFilter(authManager, userDetailsService, userService, tokenService));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(provider);
    }
}
